package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.api.db.UserReportApi;
import com.tanhua.dubbo.api.mapper.UserReportMapper;
import com.tanhua.model.db.UserReport;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Jin L
 * @date: 2021/12/27 10:51
 */
@DubboService
public class UserReportApiImpl implements UserReportApi {

    @Autowired
    private UserReportMapper userReportMapper;

    @Override
    public UserReport findPersonalReport(Long id) {
        return userReportMapper.selectById(id);
    }

    @Override
    public List<Long> findSimilarUserIdByMaxValue(String maxValue,Long wenjuan) {
        List<Long> list = new ArrayList<>();
        QueryWrapper<UserReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("max_value", maxValue);
        queryWrapper.eq("questionnaire_id",wenjuan);
        List<UserReport> userReports = userReportMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(userReports)) {
            list = userReports.stream().map(UserReport::getUserId).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public Long insertOrUpdate(UserReport userReport) {
        QueryWrapper<UserReport> queryWrapper = new QueryWrapper<>();
        Long userId = userReport.getUserId();
        Long questionnaireId = userReport.getQuestionnaireId();
        queryWrapper.eq("user_id", userId).eq("questionnaire_id", questionnaireId);
        UserReport userReportInDB = userReportMapper.selectOne(queryWrapper);
        if (null != userReportInDB) {
            Long id = userReportInDB.getId();
            userReport.setId(id);
            BeanUtils.copyProperties(userReport, userReportInDB);
            userReportMapper.updateById(userReportInDB);
        } else {
            userReportMapper.insert(userReport);
        }
        return userReport.getId();
    }
}
